package org.jpro.modules.system.web;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jpro.annotation.FormatResponseBodyAnnotation;
import org.jpro.common.web.BaseController;
import org.jpro.modules.system.entity.User;
import org.jpro.modules.system.service.IUserRoleService;
import org.jpro.modules.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import lombok.extern.slf4j.Slf4j;

/**
 * 用户controller
 */
@Slf4j
@Controller
@RequestMapping("/system/user")
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserRoleService userRoleService;

    /**
     * 默认页面
     */
    @RequestMapping(method = RequestMethod.GET)
    public String list() {
        return "system/userList";
    }

    /**
     * 获取用户json
     */
    @ResponseBody
    @RequiresPermissions("sys:user:view")
    @FormatResponseBodyAnnotation(false)
    @RequestMapping(value = "json", method = RequestMethod.GET)
    public Map<String, Object> getData(String name, String phone, Date gtCreateDate, Date ltCreateDate) {
        return getEasyUIData(userService.search(name, phone, gtCreateDate, ltCreateDate, super.getPageRequest()));
    }

    /**
     * 添加用户跳转
     */
    @RequiresPermissions("sys:user:add")
    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String createForm(Map model) {
        model.put("user", new User());
        model.put("action", "create");
        return "system/userForm";
    }

    /**
     * 添加用户
     */
    @ResponseBody
    @RequiresPermissions("sys:user:add")
    @RequestMapping(value = "create", method = RequestMethod.POST)
    public void create(@Valid User user) {
        userService.save(user);
    }

    /**
     * 修改用户跳转
     */
    @RequiresPermissions("sys:user:update")
    @RequestMapping(value = "update/{id}", method = RequestMethod.GET)
    public String updateForm(@PathVariable("id") Integer id, Map model) {
        model.put("user", userService.get(id));
        model.put("action", "update");
        return "system/userForm";
    }

    /**
     * 修改用户
     */
    @ResponseBody
    @RequiresPermissions("sys:user:update")
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public void update(@Valid @ModelAttribute @RequestBody User user) {
        userService.update(user);
    }

    /**
     * 删除用户
     */
    @ResponseBody
    @RequiresPermissions("sys:user:delete")
    @RequestMapping(value = "delete/{id}")
    public void delete(@PathVariable("id") Integer id) {
        userService.delete(id);
    }

    /**
     * 弹窗页-用户拥有的角色
     */
    @RequiresPermissions("sys:user:roleView")
    @RequestMapping(value = "{userId}/userRole")
    public String getUserRole(@PathVariable("userId") Integer id, Map model) {
        model.put("userId", id);
        return "system/userRoleList";
    }

    /**
     * 获取用户拥有的角色ID集合
     */
    @ResponseBody
    @RequestMapping(value = "{id}/role")
    @RequiresPermissions("sys:user:roleView")
    public List<Integer> getRoleIdList(@PathVariable("id") Integer id) {
        return userRoleService.getRoleIdList(id);
    }

    /**
     * 修改用户拥有的角色
     */
    @ResponseBody
    @RequiresPermissions("sys:user:roleUpd")
    @RequestMapping(value = "{id}/updateRole")
    public void updateUserRole(@PathVariable("id") Integer id, @RequestBody List<Integer> newRoleList) {
        userRoleService.updateUserRole(id, userRoleService.getRoleIdList(id), newRoleList);
    }

    /**
     * 修改密码跳转
     */
    @RequestMapping(value = "updatePwd", method = RequestMethod.GET)
    public String updatePwdForm(Model model) {
        model.addAttribute("user", session.getAttribute("user"));
        return "system/updatePwd";
    }

    /**
     * 修改密码
     */
    @ResponseBody
    @RequestMapping(value = "updatePwd", method = RequestMethod.POST)
    public String updatePwd(String oldPassword, @Valid @ModelAttribute @RequestBody User user, HttpSession session) {
        if (userService.checkPassword((User) session.getAttribute("user"), oldPassword)) {
            userService.updatePwd(user);
            session.setAttribute("user", user);
            return "success";
        } else {
            return "fail";
        }

    }

    /**
     * Ajax请求校验loginName是否唯一。
     */
    @ResponseBody
    @RequestMapping(value = "checkLoginName")
    public String checkLoginName(String loginName) {
        if (userService.getUser(loginName) == null) {
            return "true";
        } else {
            return "false";
        }
    }

    /**
     * ajax请求校验原密码是否正确
     */
    @ResponseBody
    @FormatResponseBodyAnnotation(false)
    @RequestMapping(value = "checkPwd")
    @RequiresPermissions("sys:user:update")
    public boolean checkPwd(String oldPassword, HttpSession session) {
        return userService.checkPassword((User) session.getAttribute("user"), oldPassword);
    }

    /**
     * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2
     * Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
     * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
     */
    @ModelAttribute
    public void getUser(@RequestParam(value = "id", defaultValue = "-1") Integer id, Map model) {
        if (id != -1) {
            model.put("user", userService.get(id));
        }
    }

}
